package com.google.precinct.client.mapper;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.InlineHyperlink;
import com.google.gwt.user.client.ui.Widget;
import com.google.precinct.client.Util;
import com.google.precinct.common.AddressInfo;

public class Map2PrecinctListPanel extends Composite {

	private static PrecinctSelectLPanelUiBinder uiBinder = GWT
			.create(PrecinctSelectLPanelUiBinder.class);

	interface PrecinctSelectLPanelUiBinder extends
			UiBinder<Widget, Map2PrecinctListPanel> {
	}

	private static final int PAGE_SIZE = 8;

	@UiField
	FlowPanel results;

	@UiField
	InlineHyperlink prevButton;

	@UiField
	InlineHyperlink nextButton;


	private int pageStart;
	private List<AddressInfo> resultList;

	private final MapRootPage ctr;

	public Map2PrecinctListPanel(MapRootPage ctr, List<AddressInfo> results) {
		this.ctr = ctr;
		initWidget(uiBinder.createAndBindUi(this));
		pageStart = 0;
		this.resultList = results;
		paginateResults();
		Util.track("/PrecinctFinder/06-PrecinctSelection");
	}

	private void paginateResults() {
		results.clear();
		for (int i = pageStart; i < resultList.size() && i - pageStart < PAGE_SIZE; i++) {
			AddressResultItem itemWidget = new AddressResultItem(
					this,
					resultList.get(i),
					resultList.get(i).getDisplayAddress(),
					resultList.get(i).getVotersCount());
			this.results.add(itemWidget);
		}
		if (pageStart == 0) {
			prevButton.setVisible(false);
		} else {
			prevButton.setVisible(true);
		}
		if (pageStart + PAGE_SIZE >= this.resultList.size())  {
			nextButton.setVisible(false);
		} else {
			nextButton.setVisible(true);
		}
	}

	@UiHandler("prevButton")
	void onPrevButton(ClickEvent event) {
		pageStart -= PAGE_SIZE;
		if (pageStart < 0) pageStart = 0;
		paginateResults();
	}

	@UiHandler("nextButton")
	void onNextButton(ClickEvent event) {
		pageStart += PAGE_SIZE;
		if (pageStart >= this.resultList.size()) pageStart -= PAGE_SIZE;
		paginateResults();
	}

	public void selectAddress(AddressInfo addressInfo) {
		Util.track("/PrecinctFinder/07-PrecinctSelected");
		ctr.mapAddress(addressInfo);
	}

}
